<template>
  <!-- 学生管理 -->
  <main class="w-full h-full dark:bg-black p-4">
    <use-table
      :columns="columns"
      :searchSelectOption="searchSelectOption"
      :allData="allData"
      :personalized="true"
      v-model:selectedRowKey="selectedRowKey"
      @modifyUserData="openModifyUserDataForm"
      v-model:visible="visible"
      :loading="loading"
      :total="total"
      @delete-select-user="deleteSelectUser"
    >
      <template #function>
        <a-tooltip placement="bottom">
          <template #title>
            <span>添加学生</span>
          </template>
          <div class="cursor-pointer text-lg text-blue-500 mr-2" @click="openAddStudentForm">
            <plus-circle-outlined />
          </div>
        </a-tooltip>
        <a-tooltip placement="bottom">
          <template #title>
            <span>删除选中学生</span>
          </template>
          <div class="cursor-pointer text-lg text-red-500" @click="deleteSelectUser">
            <close-circle-outlined />
          </div>
        </a-tooltip>
      </template>
      <template #title> 学生管理 </template>
    </use-table>
    <modify-form v-model:visible="visible" :modal-title-text="modalTitleText" @handleOk="handleOk">
      <template #container>
        <div>
          <div class="flex items-center">
            <span class="w-18 text-right"> 姓名： </span>
            <a-input v-model:value="modifyUserInfoFrom.username" />
          </div>
          <div class="flex mt-3 items-center">
            <span class="w-18 text-right">密码：</span>
            <a-input v-model:value="modifyUserInfoFrom.password" />
          </div>
          <div class="flex mt-3 items-center">
            <span class="w-18 text-right">身份证：</span>
            <a-input v-model:value="modifyUserInfoFrom.id_card" />
          </div>
          <div class="flex mt-3 items-center">
            <span class="w-15 text-right">性别：</span>
            <a-select ref="select" v-model:value="modifyUserInfoFrom.sex" style="width: 120px">
              <a-select-option :value="1">男</a-select-option>
              <a-select-option :value="0">女</a-select-option>
            </a-select>
          </div>
          <div class="flex mt-3 items-center">
            <span class="w-15 text-right"> 状态： </span>
            <a-switch
              :checked="modifyUserInfoFrom.status === 0 ? false : true"
              checked-children="启用"
              un-checked-children="禁用"
              @click="
                modifyUserInfoFrom.status === 0
                  ? (modifyUserInfoFrom.status = 1)
                  : (modifyUserInfoFrom.status = 0)
              "
            />
          </div>
          <div class="flex mt-3 items-center">
            <span class="w-15 text-right">班级：</span>
            <a-select
              ref="select"
              v-model:value="modifyUserInfoFrom.class_name"
              style="width: 180px"
            >
              <a-select-option v-for="i in classList" :key="i.class_name" :value="i.class_name">
                {{ i.class_name }}
              </a-select-option>
            </a-select>
          </div>
          <div class="mt-3 flex items-center">
            <span class="w-17 text-right">手机号：</span>
            <a-input v-model:value="modifyUserInfoFrom.tel" />
          </div>
          <div class="mt-3 flex items-center">
            <span class="w-17 text-right">地址：</span>
            <a-input v-model:value="modifyUserInfoFrom.address" />
          </div>
        </div>
      </template>
    </modify-form>
    <modify-form
      v-model:visible="addStudentModalVisible"
      modal-title-text="添加学生"
      @handleOk="completeAddStudentForm"
    >
      <template #container>
        <div>
          <div class="flex items-center">
            <span class="w-18 text-right"> 姓名： </span>
            <a-input v-model:value="addUserInfoFrom.username" />
          </div>
          <div class="flex items-center mt-3">
            <span class="w-18 text-right"> 密码： </span>
            <a-input v-model:value="addUserInfoFrom.password" />
          </div>
          <div class="flex mt-3 items-center">
            <span class="w-18 text-right">身份证：</span>
            <a-input v-model:value="addUserInfoFrom.id_card" />
          </div>
          <div class="flex mt-3 items-center">
            <span class="w-15 text-right">性别：</span>
            <a-select ref="select" v-model:value="addUserInfoFrom.sex" style="width: 120px">
              <a-select-option :value="1">男</a-select-option>
              <a-select-option :value="0">女</a-select-option>
            </a-select>
          </div>
          <div class="flex mt-3 items-center">
            <span class="w-15 text-right"> 状态： </span>
            <a-switch
              :checked="addUserInfoFrom.status === 0 ? false : true"
              checked-children="启用"
              un-checked-children="禁用"
              @click="
                addUserInfoFrom.status === 0
                  ? (addUserInfoFrom.status = 1)
                  : (addUserInfoFrom.status = 0)
              "
            />
          </div>
          <div class="flex mt-3 items-center">
            <span class="w-15 text-right">班级：</span>
            <a-select ref="select" v-model:value="addUserInfoFrom.className" style="width: 180px">
              <a-select-option v-for="i in classList" :key="i.key" :value="i.class_name">
                {{ i.class_name }}
              </a-select-option>
            </a-select>
          </div>
          <div class="mt-3 flex items-center">
            <span class="w-18 text-right">手机号：</span>
            <a-input v-model:value="addUserInfoFrom.tel" />
          </div>
          <div class="mt-3 flex items-center">
            <span class="w-18 text-right">地址：</span>
            <a-input v-model:value="addUserInfoFrom.address" />
          </div>
        </div>
      </template>
    </modify-form>
  </main>
</template>

<script setup lang="ts">
  import {
    getAllStudent,
    deleteSelectStudent,
    modifyStudentInfo,
    getAllClass,
    addStudent,
  } from '@/api/student';
  import { message } from 'ant-design-vue';
  import { CloseCircleOutlined, PlusCircleOutlined } from '@ant-design/icons-vue';
  import { ClassInfo } from '@/utils/interface';

  let classList = ref<ClassInfo[]>([]);
  onActivated(() => {
    getAllClass().then(({ data }) => {
      classList.value = data as ClassInfo[];
    });
  });
  const searchSelectOption: { value: string; label: string }[] = [
    {
      value: 'username',
      label: '姓名',
    },
    {
      value: 'class_name',
      label: '班级',
    },
    {
      value: 'major_name',
      label: '专业',
    },
    {
      value: 'tel',
      label: '手机号',
    },
    {
      value: 'class_teacher',
      label: '班主任',
    },
  ];

  let loading = ref(false);

  // 表头
  const columns = reactive([
    {
      title: '学生名字',
      dataIndex: 'username',
      align: 'center',
      width: 80,
    },
    {
      title: '密码',
      dataIndex: 'password',
      align: 'center',
      width: 60,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      align: 'center',
      width: 60,
    },
    {
      title: '班级',
      dataIndex: 'class_name',
      align: 'center',
      width: 100,
      ellipsis: true,
    },
    {
      title: '班主任',
      dataIndex: 'class_teacher',
      align: 'center',
      width: 80,
    },
    {
      title: '电话',
      dataIndex: 'tel',
      align: 'center',
      width: 80,
    },
    {
      title: '专业名称',
      align: 'center',
      width: 100,
      dataIndex: 'major_name',
    },
    {
      title: '状态',
      align: 'center',
      width: 70,
      dataIndex: 'status',
    },
    {
      title: '地址',
      align: 'center',
      width: 140,
      dataIndex: 'address',
      ellipsis: true,
    },
    {
      title: '添加时间',
      align: 'center',
      width: 110,
      dataIndex: 'add_time',
      sorter: (a, b) => a.add_time - b.add_time,
    },
    {
      title: '操作',
      align: 'center',
      width: 70,
      dataIndex: 'operation',
    },
  ]);
  // 修改学生信息的性别选项
  let sexValue = ref('男');
  let allData = ref([]);
  let total = ref(0);
  const getStudents = async () => {
    loading.value = true;
    const { data } = await getAllStudent();
    allData.value = data;
    total.value = data.length;
    loading.value = false;
  };
  getStudents();

  const myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
  const card = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  // 添加
  let addUserInfoFrom = ref<{
    username: string;
    password: string;
    sex: string;
    status: number;
    className: string;
    tel: string;
    address: string;
    id_card: string;
  }>({
    username: '',
    password: '',
    status: 0,
    sex: '',
    className: '',
    tel: '',
    address: '',
    id_card: '',
  });
  // 添加学生弹窗
  let addStudentModalVisible = ref(false);
  // 打开添加学生弹窗
  const openAddStudentForm = () => {
    addUserInfoFrom.value = {
      username: '',
      password: '',
      status: 0,
      sex: '',
      className: '',
      tel: '',
      address: '',
      id_card: '',
    };
    addStudentModalVisible.value = true;
  };
  // 完成添加学生
  const completeAddStudentForm = async () => {
    const {
      username,
      password,
      sex,
      className: class_name,
      tel,
      address,
      status: addStatus,
      id_card,
    } = addUserInfoFrom.value;
    if (!username || !password || !class_name || !tel || !address || !id_card) {
      message.warning('请填写完整信息');
      return;
    }
    if (!myreg.test(tel)) {
      message.warning('手机号输入错误');
      return;
    }
    if (!card.test(id_card)) {
      message.warning('身份证号输入错误');
      return;
    }
    const { status } = await addStudent({
      username,
      password,
      sex,
      class_name,
      tel,
      address,
      status: addStatus,
      id_card,
    });
    if (status === 200) {
      message.success('添加成功');
      addStudentModalVisible.value = false;
      addUserInfoFrom.value = {
        username: '',
        password: '',
        status: 0,
        sex: '',
        className: '',
        tel: '',
        address: '',
        id_card: '',
      };
      addUserInfoFrom.value.status = 0;
      await getStudents();
    }
  };
  // 勾选的数据的key
  let selectedRowKey = ref<number[] | string[]>([]);
  // 删除学生
  const deleteSelectUser = async (key: number[] | string[] | any) => {
    const selectKey = Array.isArray(key) ? key : selectedRowKey.value;
    if (selectKey.length === 0) {
      message.error('请选择要删除的学生');
      return;
    }
    const res = await deleteSelectStudent(selectKey);
    if (res.status === 200) {
      message.success('删除成功');
      getStudents();
    }
  };
  interface ModifyUserFrom {
    username: string;
    password: string;
    sex: string;
    status: number;
    class_name: string;
    key: number;
    tel: string;
    address: string;
    id_card: string;
  }
  // 修改用户表单
  let modifyUserInfoFrom = ref<ModifyUserFrom>({
    username: '',
    password: '',
    status: 0,
    key: 0,
    sex: '',
    class_name: '',
    tel: '',
    address: '',
    id_card: '',
  });
  let visible = ref(false);
  let modalTitleText = ref('修改学生信息');
  // 点击修改按钮
  const openModifyUserDataForm = (key: number) => {
    const clickUser = allData.value.find((item: any) => item.key === key) as any;
    if (clickUser !== undefined) {
      modalTitleText.value = `修改 ${clickUser.username} 的信息`;
      modifyUserInfoFrom.value = {
        ...clickUser,
      };
      sexValue.value = clickUser.sex;
      visible.value = true;
    } else message.error('发生错误');
  };
  const handleOk = async () => {
    const { username, password, sex, class_name, tel, address, status, id_card, key } =
      modifyUserInfoFrom.value;
    if (!username || !password || !sex || !class_name || !tel || !address || !id_card) {
      message.warning('请填写完整信息');
      return;
    }
    if (!myreg.test(tel)) {
      message.warning('手机号输入错误');
      return;
    }
    if (!card.test(id_card)) {
      message.warning('身份证号输入错误');
      return;
    }
    const res = await modifyStudentInfo({
      id: key,
      username,
      password,
      sex,
      class_name,
      tel,
      address,
      status,
      id_card,
    });
    if (res.status === 200) {
      message.success('修改成功');
      getStudents();
      visible.value = false;
    }
  };
</script>
